<template>
  <div>
    <a-card>
      <h2>角色管理</h2>
      <a-divider></a-divider>
      <a-button type="primary" @click="showAddModal=true">添加用户</a-button>
      <a-divider></a-divider>
      <div class="search">
        <a-input-search placeholder="请根据用户名进行搜索" enter-button v-model:value="keyword" @search="onSearch" />
        <a v-if="isSearch" href="javascript:;" @click="back">返回</a>
        <div>
          <a-button @click="showAddModal = true">添加用户</a-button>
          &nbsp;
          <a-upload action="http://localhost:3000/upload/file" @change="onUploadChange">
            <!-- :headers="headers" -->
            <a-button type="primary">Excel上传</a-button>
          </a-upload>
        </div>
      </div>
      <a-table :rowKey="(record,index)=> index" :pagination="false" :columns="columns" :data-source='list' bordered :scroll="{  y: 300 }">
        <template #createdAt="{record}">
          <!-- {{record}} -->
          {{formatTimestamp(record.meta.createdAt)}}
        </template>
        <template #character="{record}">
          <a href="javascript:;" @click="onEdit(record)">

            <EditOutlined />
          </a>
          {{ getCharacterInfoById(record.character).title}}
        </template>
        <template #actions="{record}">
          <a href="javascript:;" @click="resetPassword(record)">重置密码 </a>&nbsp;
          <a href="javascript:;" @click="remove(record)">删除</a>
        </template>
      </a-table>

      <a-pagination v-if="!isSearch" v-model:current="curPage" :total="total" :page-size="10" @change="setPage"></a-pagination>
      <add-one v-model:show="showAddModal" @getList='addOne'></add-one>
      <a-modal v-model:visible="showCharacterModal" title="修改角色" @ok="updateCharacter">
        <a-select v-model:value="editForm.character" style="width:220px">
          <a-select-option v-for="item in characterInfo" :key="item._id" :value="item._id">{{item.title}}</a-select-option>
        </a-select>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { EditOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { defineComponent, ref, onMounted, reactive } from "vue";
import { user } from "@/service";
import { result } from "@/utils/result.js";
import { formatTimestamp } from "@/utils/formatTimestamp.js";
import AddOne from "./components/AddOne.vue";
import { getCharacterInfoById } from "@/utils/character.js";
import store from "@/store/index.js";
const columns = [
  {
    title: "账户",
    dataIndex: "username",
  },
  {
    title: "创建日期",
    slots: {
      customRender: "createdAt",
    },
  },
  {
    title: "角色",
    slots: {
      customRender: "character",
    },
  },

  {
    title: "操作",
    slots: {
      customRender: "actions",
    },
  },
];
export default defineComponent({
  components: {
    AddOne,
    EditOutlined,
  },
  setup() {
    const list = ref([]);
    const total = ref(0);
    const curPage = ref(1);

    const getUser = async () => {
      const res = await user.list(curPage.value, 10, keyword.value);
      result(res).success(({ data: { list: resList, total: resTotal } }) => {
        list.value = resList;
        total.value = resTotal;
      });
    };
    onMounted(() => {
      getUser();
    });
    //_id解构出record的_id属性
    const remove = async ({ _id }) => {
      const res = await user.remove(_id);
      result(res).success(() => {
        getUser();
      });
    };
    const showAddModal = ref(false);
    const setPage = (page) => {
      curPage.value = page;
      getUser();
    };
    const addOne = () => {
      getUser();
    };
    const resetPassword = async ({ _id }) => {
      const res = await user.resetPassword(_id);
      result(res).success(() => {});
    };

    const keyword = ref("");
    const isSearch = ref(false);
    const onSearch = () => {
      getUser();
      isSearch.value = !!keyword.value; //keyword有值，搜索状态
    };
    const back = () => {
      isSearch.value = false;
      keyword.value = "";
      getUser();
    };

    const showCharacterModal = ref(false);
    const editForm = reactive({
      character: "",
      current: {},
    });
    const onEdit = (record) => {
      editForm.current = record;
      editForm.character = record.character;
      showCharacterModal.value = true;
    };
    const updateCharacter = async () => {
      const res = await user.editCharacter(
        editForm.character,
        editForm.current._id
      ); //用户id
      result(res).success(() => {
        showCharacterModal.value = false;
        //同步列表展示的值
        editForm.current.character = editForm.character;
      });
    };

    const onUploadChange = async ({ file }) => {
      console.log("file", file);
      if (file.response) {
        let key = file.response.data;
        const res = await user.addMany(key);
        console.log("res1212", res);
        if (res.data.code == 200) {
          message.success(`成功添加 ${res.data.data.addCount} 位用户`);
          getUser();
        }
      }
    };

    return {
      list,
      total,
      curPage,
      columns,
      formatTimestamp,
      remove,
      showAddModal,
      setPage,
      addOne,
      resetPassword,

      keyword,
      isSearch,
      onSearch,
      back,
      getCharacterInfoById,

      showCharacterModal,
      editForm,
      onEdit,
      characterInfo: store.state.characterInfo,
      updateCharacter,
      onUploadChange,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-pagination) {
  text-align: right;
  margin-top: 10px;
}
.search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  a {
    width: 100px;
    margin-left: 6px;
    margin-right: auto;
  }
}
:deep(.ant-input-search) {
  width: 400px;
}
</style>